var mongo = require("../mongo/mongo");

var validator = require("validator");
var moment = require("moment");
var py = require("../comm/py");
var dContract = require("../dict/dContract")
var mongoose = require('mongoose');
var array = require("../comm/array")
var yz = require("../comm/yz")
const dCustomerOrder = require('../dict/customerOrder');
var math = require("mathjs");

exports.addCustomerOrder = async function (contractId, customerOrderId) {
    // body...
    var contract = await mongo.findOneAsync({
        data: {
            _id: contractId
        },
        collection: "contract"
    });
    contract = dContract.fmtContract(contract);


    contract.customerOrderIdArray.push(mongoose.Types.ObjectId(customerOrderId));

    contract.customerOrderIdArray = array.unique(contract.customerOrderIdArray);  //去重



};

exports.removeCustomerOrder = async function (contractId, customerOrderId) {
    // body...

    var contract = await mongo.findOneAsync({
        data: {
            _id: contractId
        },
        collection: "contract"
    });






};

exports.count = async function (contractId) {
    // body...

    if (!contractId) {
        return
    }

    var customerOrderArray = await mongo.findAsync({
        data: {
            "contractInfo._id": contractId.toString()
        },
        collection: "customerOrder"
    })
    customerOrderArray = customerOrderArray.list

    var statusNum = 0
    var statusId = 0
    var reAmount = 0;
    var amount = 0;
    customerOrderArray.forEach(function (customerOrder) {
        statusNum = statusNum + yz.IsNullThen(customerOrder.statusId, 0)
        customerOrder = dCustomerOrder.fmtCustomerOrder(customerOrder)
        reAmount = math.chain(customerOrder.count.reAmount).add(reAmount).round(2).value;
        amount = math.chain(customerOrder.count.amount).add(amount).round(2).value;

    }, this);

    if (statusNum > 0) {
        statusId = 200
        if (statusNum >= customerOrderArray.length * 300) {
            statusId = 300
        }

    }




    await mongo.upAsync({
        updateFind: {
            _id: mongoose.Types.ObjectId(contractId)

        }, updateSet: {
            $set: {
                statusId: statusId,
                count: {
                    reAmount: reAmount,
                    amount: amount
                }
            }

        },
        collection: "contract"
    })

    return







};